package com.block.product.service.union;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static cn.hutool.crypto.Padding.PKCS5Padding;

@Service
public class QuJiHuaUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(true);
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String mobile = uniLoginDTO.getMobile();

        String apiCode = apiInfoParam.getApiCode();
        Long channelFlag = Long.valueOf(apiCode);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", mobile);
        paramMap.put("channelFlag",channelFlag);

        log.info("【趣记花】联登开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【趣记花】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");

        loginResult.setCode(String.valueOf(code));
        loginResult.setMessage(message);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));

        if (StrUtil.equals(String.valueOf(code), "1000")) {
            String data = resultObject.getString("url");
            loginResult.setSuccess(true);
            loginResult.setLoginUrl(data);
        }
        return loginResult;
    }


}
